import React, { Component } from 'react';
import { List, Divider, Avatar, Skeleton, Spin, Pagination } from 'antd';
import { query,dateFmt } from '../utils/utils';

import { Link } from 'react-router-dom';

class Lists extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      pageSize: 10,
      defaultPageSize: 10,
      lists: [],
      isLoading: true
    }
  }
  // 每页显示数据条数更新回调
  pageSizeChange(page,pageSize) {
    console.log(pageSize);
    this.setState({
      pageSize
    }, () => {
      this.getList();
    });
  }
  // 页码更新回调函数
  pageChange(page) {
    this.setState({
      page
    }, () => {
      this.getList();
    });
  }
  // 请求文章列表
  getList() {
    query(`/topics?page=${this.state.page}&limit=${this.state.pageSize}`).then(res => {

      setTimeout(() => {
        this.setState({
          lists: res.data
        });
      }, 1000);
      setTimeout(() => {
        this.setState({
          isLoading: false
        });
      }, 2000);
    })
  }
  componentWillMount() {
    this.getList();
  }
  render() {
    return (
      <div>
        {
          this.state.lists.length > 0 ? <List
            itemLayout="horizontal"
            dataSource={this.state.lists}
            renderItem={item => (
              <List.Item>
                <Skeleton size="large" avatar title={true} loading={this.state.isLoading} active>
                  <List.Item.Meta
                    avatar={<Avatar size={80} src={item.author.avatar_url} />}
                    title={<Link to={"/detail/"+item.id}>{item.title}</Link>}
                    description={dateFmt(item.create_at)}
                  />
                </Skeleton>
              </List.Item>
            )}
          /> : <div style={{ textAlign: 'center' }}><Spin size="large" /></div>
        }

        <Divider />
        <Pagination onShowSizeChange={this.pageSizeChange.bind(this)} onChange={this.pageChange.bind(this)} defaultCurrent={this.state.page} total={500} />

      </div>
    );
  }
}

export default Lists;
